"""
全局异常处理器
处理系统中所有未捕获的异常，提供统一的错误响应格式
"""

import logging
import traceback
from fastapi import Request
from fastapi.responses import JSONResponse
from exception.exceptions import (
    BusinessException,
    DatabaseException,
    ValidationException,
    AuthenticationException,
    PermissionException,
    ResourceNotFoundException
)

logger = logging.getLogger(__name__)


async def global_exception_handler(request: Request, exc: Exception):
    """
    全局异常处理器
    捕获所有未被特定处理器处理的异常

    Args:
        request: 请求对象
        exc: 异常对象

    Returns:
        JSONResponse: 统一的错误响应
    """
    # 记录异常堆栈信息
    logger.error(f"全局异常捕获: {str(exc)}")
    logger.error(f"异常类型: {type(exc).__name__}")
    logger.error(f"请求URL: {request.url}")
    logger.error(f"请求方法: {request.method}")
    logger.error("异常堆栈信息:")
    logger.error(traceback.format_exc())

    # 根据异常类型返回不同的错误响应
    error_response = {
        "success": False,
        "error": {
            "code": 500,
            "message": "服务器内部错误",
            "type": "InternalServerError",
            "path": str(request.url.path),
            "details": {}
        }
    }

    # 处理自定义异常
    if isinstance(exc, BusinessException):
        error_response["error"].update({
            "code": exc.code,
            "message": exc.message,
            "type": "BusinessError",
            "details": exc.details
        })
        status_code = exc.code
    elif isinstance(exc, DatabaseException):
        error_response["error"].update({
            "code": exc.code,
            "message": exc.message,
            "type": "DatabaseError",
            "details": exc.details
        })
        status_code = exc.code
    elif isinstance(exc, ValidationException):
        error_response["error"].update({
            "code": exc.code,
            "message": exc.message,
            "type": "ValidationError",
            "details": exc.details
        })
        status_code = exc.code
    elif isinstance(exc, AuthenticationException):
        error_response["error"].update({
            "code": exc.code,
            "message": exc.message,
            "type": "AuthenticationError",
            "details": exc.details
        })
        status_code = exc.code
    elif isinstance(exc, PermissionException):
        error_response["error"].update({
            "code": exc.code,
            "message": exc.message,
            "type": "PermissionError",
            "details": exc.details
        })
        status_code = exc.code
    elif isinstance(exc, ResourceNotFoundException):
        error_response["error"].update({
            "code": exc.code,
            "message": exc.message,
            "type": "ResourceNotFoundError",
            "details": exc.details
        })
        status_code = exc.code
    else:
        # 处理其他所有未预期的异常
        # 在生产环境中，不建议将详细错误信息返回给客户端
        from config import DEBUG  # 导入配置
        if DEBUG:
            error_response["error"]["details"] = {
                "exception_type": type(exc).__name__,
                "exception_message": str(exc),
                "traceback": traceback.format_exc().split('\n')
            }
        else:
            error_response["error"]["details"] = {"message": "服务器内部错误，请联系管理员"}
        status_code = 500

    return JSONResponse(status_code=status_code, content=error_response)


async def not_found_exception_handler(request: Request, exc: Exception):
    """处理404未找到异常"""
    logger.warning(f"404错误 - 请求路径不存在: {request.url}")
    return JSONResponse(
        status_code=404,
        content={
            "success": False,
            "error": {
                "code": 404,
                "message": "请求的资源不存在",
                "type": "NotFoundError",
                "path": str(request.url.path)
            }
        }
    )


async def validation_exception_handler(request: Request, exc: Exception):
    """处理422参数验证异常"""
    logger.warning(f"422错误 - 请求参数验证失败: {request.url}")
    return JSONResponse(
        status_code=422,
        content={
            "success": False,
            "error": {
                "code": 422,
                "message": "请求参数验证失败",
                "type": "ValidationError",
                "path": str(request.url.path)
            }
        }
    )


def register_exception_handlers(app):
    """
    注册所有异常处理器到FastAPI应用
    """
    # 注册全局异常处理器
    app.add_exception_handler(Exception, global_exception_handler)

    # 注册特定HTTP状态码异常处理器
    app.add_exception_handler(404, not_found_exception_handler)
    app.add_exception_handler(422, validation_exception_handler)

    # 注册自定义异常处理器
    app.add_exception_handler(BusinessException, global_exception_handler)
    app.add_exception_handler(DatabaseException, global_exception_handler)
    app.add_exception_handler(ValidationException, global_exception_handler)
    app.add_exception_handler(AuthenticationException, global_exception_handler)
    app.add_exception_handler(PermissionException, global_exception_handler)
    app.add_exception_handler(ResourceNotFoundException, global_exception_handler)

    logger.info("全局异常处理器注册完成")


# from exceptions import BusinessException, ResourceNotFoundException
# from response_utils import success_response, error_response
#
# @app.get("/api/users/{user_id}")
# async def get_user(user_id: int):
#     try:
#         # 业务逻辑
#         user = await get_user_by_id(user_id)
#         if not user:
#             raise ResourceNotFoundException(
#                 message="用户不存在",
#                 details={"user_id": user_id}
#             )
#
#         return success_response(data=user, message="获取用户信息成功")
#
#     except ResourceNotFoundException:
#         # 重新抛出，让全局异常处理器处理
#         raise
#     except Exception as e:
#         # 记录错误并抛出业务异常
#         logger.error(f"获取用户信息失败: {str(e)}")
#         raise BusinessException(
#             message="获取用户信息失败",
#             details={"user_id": user_id, "error": str(e)}
#         )